package com.example.demo.web;

import com.example.demo.dao.StuMapper;
import com.example.demo.dao.TeaMapper;
import com.example.demo.entity.Stu;
import com.example.demo.entity.Tea;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("stu")
@Controller
public class StuController {
    @Autowired
    StuMapper stuMapper;
    @Autowired
    TeaMapper teaMapper;

    @RequestMapping("list")
    @ResponseBody
    public List<Stu> list() {
        List<Stu> list = stuMapper.list();
        return list;
    }

    @GetMapping("add")
    public String add() {
        return "/stu/add";
    }


    @PostMapping("add")
    public String add(Stu stu) {
        stuMapper.save(stu);
        return "redirect:/stu/listhtml";
    }

    @GetMapping("addtea")
    public String addtea() {
        return "/stu/addtea";
    }


    @PostMapping("addtea")
    public String addtea(Tea tea) {
        teaMapper.save(tea);
        return "redirect:/stu/listhtml";
    }

    @RequestMapping("listhtml")
    public String listhtml(ModelMap map) {
        List<Stu> list = stuMapper.list();
        List<Tea> list2 = teaMapper.list();
        map.put("stulist", list);
        map.put("tealist", list2);
        map.put("size", list.size());
        int sum = 0;
        int sum1 = 0;
        for (Tea tea : list2) {
            sum1 += tea.getTeanum();
        }
        for (Stu stu : list) {
            sum += stu.getStunum();
        }
        map.put("teasum", sum1);
        map.put("sum", sum);
        return "/stu/index";
    }

    @GetMapping("delete/{id}")
    public String delete(@PathVariable("id") Integer id) {
        stuMapper.delete(id);
        return "redirect:/stu/listhtml";
    }

    @GetMapping("deletetea/{id}")
    public String deletetea(@PathVariable("id") Integer id) {
        teaMapper.delete(id);
        return "redirect:/stu/listhtml";
    }

    @GetMapping("edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap map) {
        map.put("stu", stuMapper.findById(id));
        return "/stu/edit";
    }

    @PostMapping("edit")
    public String edit(Stu stu) {
        stuMapper.update(stu);
        return "redirect:/stu/listhtml";
    }

    @GetMapping("edittea/{id}")
    public String edittea(@PathVariable("id") Integer id, ModelMap map) {
        map.put("tea", teaMapper.findById(id));
        return "/stu/edittea";
    }

    @PostMapping("edittea")
    public String edittea(Tea tea) {
        teaMapper.update(tea);
        return "redirect:/stu/listhtml";
    }
}
